package cn.itlaobing.eshop.web.servlet;/**
 * Created by 1223 on 2017/11/15.
 */

import cn.itlaobing.eshop.entity.MsgToken;
import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;


/**
 * 类名：
 * 描述：
 * 作者：陈志凯
 * 时间：2017/11/15
 */
@WebServlet("/msgSend")
public class MsgSendServlet extends HttpServlet{
    Logger logger=Logger.getLogger(MsgSendServlet.class);
    public static final String MSG_TOKEN_IN_SESSION="MSG_TOKEN_IN_SESSION";



    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取手机号码
        String phone=request.getParameter("username");

        //手机号码有效性验证

        HttpSession session=request.getSession();
        MsgToken msgToken=(MsgToken)session.getAttribute(MSG_TOKEN_IN_SESSION);
        if(msgToken!=null){//已经存在
            long diff=System.currentTimeMillis()-msgToken.getCrateAt();
            if(diff<60*1000){//错误，不允许发送验证码
                Map<String,Object> result=new HashMap<>();
                result.put("success",false);
                result.put("msg","验证码已经发送");
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(result));
                return;
            }
        }

        //不存在
        msgToken=new MsgToken();
        msgToken.setCrateAt(System.currentTimeMillis());
        msgToken.setPhone(phone);
        String msgCode=genMsgCode();
        msgToken.setMsgCode(msgCode);
        logger.info("短信验证码："+msgCode);
        session.setAttribute(MSG_TOKEN_IN_SESSION,msgToken);

        Map<String,Object> result=new HashMap<>();
        result.put("success",true);
        result.put("msg","验证码已经发送");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(result));


    }
    private String genMsgCode(){
        String number="0123456789";
        Random r=new Random(System.currentTimeMillis());
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<6;i++){
            int index=r.nextInt(number.length());
            sb.append(number.charAt(index));
        }
        return sb.toString();
    }
}
